package cn.woblog.android.httputils.manager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.woblog.android.httputils.domain.Request;

public class RequestManager {
	private static RequestManager mRequestManager;
	private Map<String, ArrayList<Request>> mRequestCache;

	private RequestManager() {
		mRequestCache = new HashMap<String, ArrayList<Request>>();
	}

	public static RequestManager getInstance() {
		if (mRequestManager == null) {
			mRequestManager = new RequestManager();
		}
		return mRequestManager;
	}

	public void cancel(String key) {
		ArrayList<Request> requests = mRequestCache.get(key);
		cancel(requests, false);
	}

	public void cancelForce(String key) {
		ArrayList<Request> requests = mRequestCache.get(key);
		cancel(requests, true);
	}

	private void cancel(ArrayList<Request> requests, boolean isForce) {
		if (requests != null) {
			for (Request request : requests) {
				request.cancel(isForce);
			}
		}
	}

	public void cancelAll() {
		innerCancelAll(false);
	}

	private void innerCancelAll(boolean isForce) {
		ArrayList<Request> value;
		for (Map.Entry<String, ArrayList<Request>> item : mRequestCache
				.entrySet()) {
			value = item.getValue();
			if (value != null) {
				cancel(value, isForce);
			}
		}
	}

	public void cancelAllForce() {
		innerCancelAll(true);
	}

	public void execute(String key, Request request) {
		ArrayList<Request> requests = mRequestCache.get(key);
		if (requests == null) {
			requests = new ArrayList<Request>();
			mRequestCache.put(key, requests);
		}
		requests.add(request);
		request.execute();
	}
}
